<template>
  <div class="admin-page admin-department">
    <div class="page-header">
      <h1>部门管理</h1>
      <div class="actions">
        <el-button type="primary" @click="openDepartmentDialog(null)">
          <el-icon><Plus /></el-icon> 新增部门
        </el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <div class="filter-container">
        <el-form :inline="true" class="filter-form">
          <el-form-item label="部门名称">
            <el-input v-model="filters.name" placeholder="请输入部门名称" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchDepartments">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredDepartments"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="部门ID" width="100" resizable></el-table-column>
        <el-table-column prop="name" label="部门名称" min-width="120" resizable></el-table-column>
        <el-table-column prop="parentName" label="上级部门" min-width="120" resizable></el-table-column>
        <el-table-column prop="departmentTypeName" label="部门类型" min-width="120" resizable></el-table-column>
        <el-table-column label="操作" fixed="right" width="200" resizable>
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDepartmentDialog(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteDepartment(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 部门编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑部门' : '新增部门'"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      @close="handleDialogClose"
    >
      <el-form :model="departmentForm" :rules="rules" ref="departmentFormRef" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <el-select v-model="departmentForm.parentId" placeholder="请选择上级部门" clearable style="width: 100%">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
              :disabled="dept.id === departmentForm.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门类型" prop="departmentTypeId">
          <el-select v-model="departmentForm.departmentTypeId" placeholder="请选择部门类型" style="width: 100%">
            <el-option
              v-for="type in departmentTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDepartmentForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, reactive, nextTick } from 'vue';
import { departmentApi } from '@/api/base-data';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';

export default {
  components: {
    Plus,
    Edit,
    Delete
  },
  setup() {
    const departments = ref([]);
    const loading = ref(false);
    const submitting = ref(false);
    const dialogVisible = ref(false);
    const departmentFormRef = ref(null);
    
    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    
    // 筛选条件
    const filters = reactive({
      name: ''
    });
    
    // 部门类型列表
    const departmentTypes = ref([]);
    
    // 部门表单
    const departmentForm = reactive({
      id: '',
      name: '',
      parentId: null,
      departmentTypeId: null
    });
    
    // 强制重置表单的方法
    const forceResetDepartmentForm = () => {
      departmentForm.id = '';
      departmentForm.name = '';
      departmentForm.parentId = null;
      departmentForm.departmentTypeId = null;
    };
    
    const isEdit = computed(() => !!departmentForm.id);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入部门名称', trigger: 'blur' }
      ],
      departmentTypeId: [
        { required: true, message: '请选择部门类型', trigger: 'change' }
      ]
    };

    const fetchDepartments = async () => {
      loading.value = true;
      try {
        departments.value = await departmentApi.getAllDepartments();
        total.value = departments.value.length;
      } catch (error) {
        console.error('获取部门列表失败:', error);
        ElMessage.error('获取部门列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    const fetchDepartmentTypes = async () => {
      try {
        departmentTypes.value = await departmentApi.getAllDepartmentTypes();
      } catch (error) {
        console.error('获取部门类型失败:', error);
        ElMessage.error('获取部门类型失败');
      }
    };
    
    // 根据筛选条件过滤数据
    const filteredDepartments = computed(() => {
      let filtered = departments.value;
      
      if (filters.name) {
        filtered = filtered.filter(dept => 
          dept.name.includes(filters.name)
        );
      }
      
      // 更新总数
      total.value = filtered.length;
      
      // 返回当前页的数据
      const startIndex = (currentPage.value - 1) * pageSize.value;
      return filtered.slice(startIndex, startIndex + pageSize.value);
    });
    
    // 搜索部门
    const searchDepartments = () => {
      currentPage.value = 1;
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.name = '';
      currentPage.value = 1;
    };
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };
    
    // 打开部门编辑对话框
    const openDepartmentDialog = async (department) => {
      // 先强制重置表单数据
      forceResetDepartmentForm();
      
      if (department) {
        // 编辑模式：填充现有数据
        departmentForm.id = department.id;
        departmentForm.name = department.name;
        departmentForm.parentId = department.parentId;
        departmentForm.departmentTypeId = department.departmentTypeId;
      }
      
      dialogVisible.value = true;
      
      // 使用 nextTick 确保对话框完全渲染后再清除验证状态
      await nextTick();
      if (departmentFormRef.value) {
        departmentFormRef.value.clearValidate();
      }
    };
    
    // 重置部门表单
    const resetDepartmentForm = async () => {
      Object.assign(departmentForm, {
        id: '',
        name: '',
        parentId: null,
        departmentTypeId: null
      });
      
      // 使用 nextTick 确保数据绑定完成后再重置表单验证
      await nextTick();
      if (departmentFormRef.value) {
        departmentFormRef.value.resetFields();
        departmentFormRef.value.clearValidate();
      }
    };
    
    // 提交部门表单
    const submitDepartmentForm = async () => {
      if (!departmentFormRef.value) return;
      
      try {
        await departmentFormRef.value.validate();
        submitting.value = true;
        
        if (isEdit.value) {
          await departmentApi.updateDepartment(departmentForm.id, departmentForm);
          ElMessage.success('更新部门成功');
        } else {
          await departmentApi.createDepartment(departmentForm);
          ElMessage.success('创建部门成功');
        }
        
        dialogVisible.value = false;
        fetchDepartments();
      } catch (error) {
        console.error('提交部门表单失败:', error);
        ElMessage.error('操作失败');
      } finally {
        submitting.value = false;
      }
    };

    // 处理对话框关闭
    const handleDialogClose = async () => {
      // 对话框关闭时强制重置表单数据
      forceResetDepartmentForm();
      
      // 使用 nextTick 确保数据绑定完成后再清除验证状态
      await nextTick();
      if (departmentFormRef.value) {
        departmentFormRef.value.clearValidate();
      }
    };

    // 删除部门
    const deleteDepartment = async (department) => {
      try {
        await ElMessageBox.confirm(`确定要删除部门 ${department.name} 吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await departmentApi.deleteDepartment(department.id);
        ElMessage.success('删除成功');
        fetchDepartments();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除部门失败:', error);
          ElMessage.error(`删除部门失败: ${error.message || '未知错误'}`);
        }
      }
    };

    onMounted(() => {
      fetchDepartments();
      fetchDepartmentTypes();
    });

    return {
      departments,
      departmentTypes,
      filteredDepartments,
      loading,
      filters,
      currentPage,
      pageSize,
      total,
      departmentForm,
      departmentFormRef,
      rules,
      dialogVisible,
      submitting,
      isEdit,
      searchDepartments,
      resetFilters,
      handlePageChange,
      openDepartmentDialog,
      submitDepartmentForm,
      deleteDepartment,
      handleDialogClose,
      forceResetDepartmentForm
    };
  }
};
</script>

<style scoped>
.admin-department {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  margin-left: auto;
}

.table-card {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-dialog__footer) {
  padding-top: 0;
}
</style>
